package com.ruoyi.web.controller.module.employee;

import com.alibaba.fastjson2.JSONArray;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.employee.domain.EmployeeDept;
import com.ruoyi.employee.domain.EmployeeUser;
import com.ruoyi.employee.service.IEmployeeDeptService;
import com.ruoyi.employee.service.IEmployeeUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 店员信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/employee/user")
public class EmployeeUserController extends BaseController
{
    @Autowired
    private IEmployeeUserService employeeUserService;

    @Autowired
    private IEmployeeDeptService deptService;

    /**
     * 获取店员列表 - 排行
     */
    @GetMapping("/employeeUserListSort")
    public AjaxResult employeeUserListSort(HttpServletRequest request)
    {
        AjaxResult ajax = AjaxResult.success();
        EmployeeUser user = new EmployeeUser();

        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            user.setShopId(shopId);
        }
        user.setActive(UserConstants.ZERO);

        /** 用户性别 0=男,1=女,2=未知 */
        user.setSex(UserConstants.ZERO);
        PageHelper.startPage(1, 3, "score desc").setReasonable(true);
        List<EmployeeUser> list_man = employeeUserService.selectUserList(user);
        ajax.put("man", list_man);
        PageHelper.clearPage();

        user.setSex(UserConstants.ONE);
        PageHelper.startPage(1, 3, "score desc").setReasonable(true);
        List<EmployeeUser> list_woman = employeeUserService.selectUserList(user);
        ajax.put("woman", list_woman);
        PageHelper.clearPage();

        user.setSex("");
        /** 在线状态（0正常 1忙碌 2下线） */
        user.setStatus(UserConstants.ZERO);
        user.setIsNewShow(UserConstants.YES);
        PageHelper.startPage(1, 5, "create_time desc").setReasonable(true);
        List<EmployeeUser> list_new = employeeUserService.selectUserList(user);
        ajax.put("new", list_new);
        PageHelper.clearPage();

        user.setSex("");
        /** 在线状态（0正常 1忙碌 2下线） */
        user.setStatus(UserConstants.ZERO);
        PageHelper.startPage(1, 5, "score_total desc").setReasonable(true);
        List<EmployeeUser> list_hot = employeeUserService.selectUserList(user);
        ajax.put("hot", list_hot);
        PageHelper.clearPage();

        return ajax;
    }

    /**
     * 获取店员列表
     */
    @PostMapping("/employeeUserList")
    public TableDataInfo list(@RequestBody EmployeeUser employeeUser, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            employeeUser.setShopId(shopId);
        }
        startPageByPost();
        List<EmployeeUser> list = employeeUserService.selectUserList(employeeUser);
        if(SecurityUtils.isLogin()){
            Long userId = SecurityUtils.getUserId();
            if (StringUtils.isNotNull(userId)){
                for(EmployeeUser eu : list){
                    String key = CacheConstants.CUSTOMER_COLLECT_EMPLOYEE + userId.toString() + "_" + eu.getUserId().toString();
                    JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject((key));
                    if (StringUtils.isNotNull(arrayCache))
                    {
                        eu.setIsLike(UserConstants.YES);
                    }else{
                        eu.setIsLike(UserConstants.NO);
                    }
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 根据店员编号获取详细信息
     */
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId))
        {
            EmployeeUser employeeUser = employeeUserService.selectUserById(userId);
            if(SecurityUtils.isLogin()){
                Long loginUserId = SecurityUtils.getUserId();
                if (StringUtils.isNotNull(userId)){
                    String key1 = CacheConstants.CUSTOMER_COLLECT_EMPLOYEE + loginUserId.toString() + "_" + employeeUser.getUserId().toString();
                    JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject((key1));
                    if (StringUtils.isNotNull(arrayCache))
                    {
                        employeeUser.setIsLike(UserConstants.YES);
                    }else{
                        employeeUser.setIsLike(UserConstants.NO);
                    }
                }
            }
            ajax.put(AjaxResult.DATA_TAG, employeeUser);
        }
        return ajax;
    }

    /**
     * 新增店员
     */
    @PreAuthorize("@ss.hasPermi('employee:user:add')")
    @Log(title = "店员管理 - 新增", businessType = BusinessType.INSERT)
    @PostMapping("/employeeUserAdd")
    public AjaxResult add(@Validated @RequestBody EmployeeUser user, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            user.setShopId(shopId);
        }
        if (!employeeUserService.checkUserNameUnique(user))
        {
            return error("新增店员'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !employeeUserService.checkPhoneUnique(user))
        {
            return error("新增店员'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !employeeUserService.checkEmailUnique(user))
        {
            return error("新增店员'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getWxId()) && !employeeUserService.checkWxIdUnique(user))
        {
            return error("新增店员'" + user.getUserName() + "'失败，微信号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(employeeUserService.insertUser(user));
    }

    /**
     * 修改店员
     */
    @PreAuthorize("@ss.hasPermi('employee:user:edit')")
    @Log(title = "店员管理 - 修改", businessType = BusinessType.UPDATE)
    @PostMapping("/employeeUserUpdate")
    public AjaxResult edit(@Validated @RequestBody EmployeeUser user)
    {
        employeeUserService.checkUserAllowed(user);
        employeeUserService.checkUserDataScope(user.getUserId());
        if (!employeeUserService.checkUserNameUnique(user))
        {
            return error("修改店员'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !employeeUserService.checkPhoneUnique(user))
        {
            return error("修改店员'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !employeeUserService.checkEmailUnique(user))
        {
            return error("修改店员'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getWxId()) && !employeeUserService.checkWxIdUnique(user))
        {
            return error("修改店员'" + user.getUserName() + "'失败，微信号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(employeeUserService.updateUser(user));
    }

    /**
     * 修改店员 - 自己修改
     */
    @PostMapping("/employeeUserUpdateInfo")
    public AjaxResult employeeUserUpdateInfo(@Validated @RequestBody EmployeeUser employeeUser)
    {
        Long userId = SecurityUtils.getUserId();
        EmployeeUser user = employeeUserService.selectUserById(userId);
        employeeUserService.checkUserAllowed(user);
        user.setWxId(employeeUser.getWxId());
        user.setQrCode(employeeUser.getQrCode());
        user.setRealName(employeeUser.getRealName());
        return toAjax(employeeUserService.updateUser(user));
    }

    /**
     * 删除店员
     */
    @PreAuthorize("@ss.hasPermi('employee:user:remove')")
    @Log(title = "店员管理 - 删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前店员不能删除");
        }
        return toAjax(employeeUserService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('employee:user:resetPwd')")
    @Log(title = "店员管理 - 重置密码", businessType = BusinessType.UPDATE)
    @PutMapping("/employeeUserResetPwd")
    public AjaxResult resetPwd(@RequestBody EmployeeUser user)
    {
        employeeUserService.checkUserAllowed(user);
        employeeUserService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(employeeUserService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('employee:user:edit')")
    @Log(title = "店员管理 - 状态修改", businessType = BusinessType.UPDATE)
    @PutMapping("/employeeUserChangeStatus")
    public AjaxResult changeStatus(@RequestBody EmployeeUser user)
    {
        employeeUserService.checkUserAllowed(user);
        employeeUserService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(employeeUserService.updateUserStatus(user));
    }


    /**
     * 状态修改
     */
    @GetMapping("/employeeChangeStatus")
    public AjaxResult employeeChangeStatus()
    {
        Long userId = SecurityUtils.getUserId();
        EmployeeUser user = employeeUserService.selectUserById(userId);
        /** 在线状态（0正常 1忙碌 2下线） */
        if(user.getStatus().equals(UserConstants.ZERO)){
            user.setStatus(UserConstants.TWO);
        }else if(user.getStatus().equals(UserConstants.TWO)){
            user.setStatus(UserConstants.ZERO);
        }
        return toAjax(employeeUserService.updateUserStatus(user));
    }


    @Log(title = "店员管理 - 导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('employee:user:export')")
    @PostMapping("/employeeUserExport")
    public void export(HttpServletResponse response, EmployeeUser user)
    {
        List<EmployeeUser> list = employeeUserService.selectUserList(user);
        ExcelUtil<EmployeeUser> util = new ExcelUtil<EmployeeUser>(EmployeeUser.class);
        util.exportExcel(response, list, "店员数据");
    }

    @Log(title = "店员管理 - 导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('employee:user:import')")
    @PostMapping("/employeeUserImportData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<EmployeeUser> util = new ExcelUtil<EmployeeUser>(EmployeeUser.class);
        List<EmployeeUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = employeeUserService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/employeeUserImportTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<EmployeeUser> util = new ExcelUtil<EmployeeUser>(EmployeeUser.class);
        util.importTemplateExcel(response, "店员数据");
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('employee:user:list')")
    @GetMapping("/employeeUserDeptTree")
    public AjaxResult deptTree(EmployeeDept dept, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            dept.setShopId(shopId);
        }
        return success(deptService.selectDeptTreeList(dept));
    }
}
